﻿/// <reference path="references.js" />
if ( !window.Gorbatras ) window.Gorbatras = {};
if ( !window.Gorbatras.Admin ) window.Gorbatras.Admin = {};

Gorbatras.Admin.FileControl = {};

//Some minor file validation and automatically fills in filename on a_targetID if it exists
Gorbatras.Admin.FileControl.FileuploadChange = function ( a_context, a_targetID, a_extensions, a_targetExtension )
{
    //TODO: error popup if doing something bad!

    $_context = $( a_context );

    var f_filename = $_context.val().toLowerCase();
    var f_okExtension = false;

    if ( Array.isArray( a_extensions ) )
    {
        f_okExtension = false;
        for ( var i = 0; i < a_extensions.length; i++ )
        {
            if ( f_filename.indexOf( a_extensions[i], f_filename.length - a_extensions[i].length ) !== -1 )
            {
                f_okExtension = true;
                break;
            }
        }
    }

    if ( !f_okExtension )
    {
        $_context.val( undefined );
        return;
    }
    
    if ( a_targetID )
    {
        $_filename = $( "#" + a_targetID );
        //If it already has value, don't overwrite that
        if ( $_filename.val() && $_filename.val() !== "" )
        {
            return;
        }
        else
        {
            $_filename.val( $_context.val() );
        }
        
        if ( a_targetExtension )
        {
            f_filename = $_filename.val();

            if ( f_filename.indexOf( a_targetExtension, f_filename.length - a_targetExtension.length ) === -1 )
            {
                $_filename.val( f_filename.substring( 0, f_filename.length - a_extensions[i].length ) + a_targetExtension );
            }
        }
        else if ( a_targetExtension === "" )
        {
            f_filename = $_filename.val();
            
            $_filename.val( f_filename.substring( 0, f_filename.length - a_extensions[i].length ) );
        }
    }
};